package com.yc.grpc;

import com.google.common.annotations.VisibleForTesting;
import com.yc.grpc.client.GrpcClient;
import com.yc.grpc.client.GrpcCommonRequest;
import com.yc.grpc.client.GrpcCommonResponse;
import com.yc.grpc.host.AbstractGrpcHost;
import com.yc.grpc.interceptor.HeaderClientInterceptor;
import com.yc.grpc.proxy.BeanInfo;
import com.yc.grpc.service.GrpcCommonServiceGrpc;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author: ZhouJianLong
 * @Date: 2024/07/19/16:49
 * @Description:
 */
@Slf4j
public class RpcInvocationHandler implements InvocationHandler {

    private BeanInfo beanInfo;
    public RpcInvocationHandler(BeanInfo beanInfo){
        this.beanInfo = beanInfo;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("grpc 端口 {} ip {}",beanInfo.getAbstractGrpcHost().port(),beanInfo.getAbstractGrpcHost().host());
        GrpcCommonRequest grpcRequest = new GrpcCommonRequest();
        grpcRequest.setArgs(args);
        grpcRequest.setMethod(method.getName());
        grpcRequest.setBeanName(beanInfo.getRpcInterface().getName());
        grpcRequest.setClazz(beanInfo.getRpcInterface().getName());
        grpcRequest.setTimeout(30);
        grpcRequest.setVersionCode(1);
        grpcRequest.setArgTypes(method.getParameterTypes());

        String packageName = beanInfo.getRpcInterface().getPackageName();
        log.info("当前包名 {}",packageName);

//        GrpcCommonServiceGrpc.GrpcCommonServiceBlockingStub blockingStub = GrpcClient.getCommonServiceBlockingStub(beanInfo.getAbstractGrpcHost().host(), beanInfo.getAbstractGrpcHost().port());
        GrpcCommonServiceGrpc.GrpcCommonServiceBlockingStub blockingStub = GrpcClient
                .getCommonServiceBlockingStubWithClientInterceptor(beanInfo.getAbstractGrpcHost().host(),
                        beanInfo.getAbstractGrpcHost().port(), new HeaderClientInterceptor("1111"));
        // grpc客户端.发起请求
        GrpcCommonResponse grpcResponse = GrpcClient.commonHandle(blockingStub, grpcRequest);
        return grpcResponse;
    }
}
